/*******************************************
Module: zt_str.c
E-Mail: 24zhutian@gmail.com
Notices: Copyright (c) 2007-2011 ls
*******************************************/
#include "zt_config.h"
#include "zt_hash.h"

static zt_inline unsigned int zt_s2i(const u_char *str, unsigned int Init, int Factor)
{
    while(*str){
        Init *= Factor;
        Init += *str++;
    }
    return Init;
}

/*
Google toolbar url hash v5
*/
ZT_API unsigned int zt_hash_google_url(const u_char *str)
{
    unsigned int C1, C2, T1, T2;
	
    C1 = zt_s2i(str, 0x1505, 0x21);
    C2 = zt_s2i(str, 0, 0x1003F);
	
    C1 >>= 2;
    C1 = ((C1 >> 4) & 0x3FFFFC0) | (C1 & 0x3F);
    C1 = ((C1 >> 4) & 0x3FFC00) | (C1 & 0x3FF);
    C1 = ((C1 >> 4) & 0x3C000) | (C1 & 0x3FFF);
	
    T1 = (C1 & 0x3C0) << 4;
    T1 |= C1 & 0x3C;
    T1 = (T1 << 2) | (C2 & 0xF0F);
	
    T2 = (C1 & 0xFFFFC000) << 4;
    T2 |= C1 & 0x3C00;
    T2 = (T2 << 0xA) | (C2 & 0xF0F0000);
	
    return (T1 | T2);
}

/*
djb2
   this algorithm (k=33) was first reported by dan bernstein many years ago in comp.lang.c.
another version of this algorithm (now favored by bernstein) uses xor:
hash(i) = hash(i - 1) * 33 ^ str[i];
   the magic of number 33 (why it works better than many other constants, prime or not)
has never been adequately explained.
*/
ZT_API unsigned int zt_hash_djb2(const u_char *str)
{
	const u_char *cp=str;
	unsigned int hash=5381;

	while(*cp){
		hash=((hash<<5)+hash)+*cp; /* hash=hash*33+c */
		cp++;
	}
	return(hash);
}